// 统一API响应格式中间件
const responseFormatter = (req, res, next) => {
  // 成功响应
  res.success = (data = null, message = '操作成功', code = 'SUCCESS') => {
    const response = {
      success: true,
      message,
      code,
      data,
      timestamp: new Date().toISOString()
    }

    // 如果data是数组且有分页信息，则将分页信息提升到顶层
    if (data && typeof data === 'object' && data.items && data.pagination) {
      response.data = data.items
      response.pagination = data.pagination
    }

    res.json(response)
  }

  // 错误响应
  res.error = (message = '操作失败', code = 'ERROR', statusCode = 400) => {
    const response = {
      success: false,
      message,
      code,
      timestamp: new Date().toISOString()
    }

    res.status(statusCode).json(response)
  }

  // 分页响应
  res.paginate = (items, page, limit, total, message = '获取成功') => {
    const totalPages = Math.ceil(total / limit)
    const hasNextPage = page < totalPages
    const hasPrevPage = page > 1

    const response = {
      success: true,
      message,
      code: 'SUCCESS',
      data: items,
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        total: parseInt(total),
        totalPages,
        hasNextPage,
        hasPrevPage,
        nextPage: hasNextPage ? page + 1 : null,
        prevPage: hasPrevPage ? page - 1 : null
      },
      timestamp: new Date().toISOString()
    }

    res.json(response)
  }

  next()
}

module.exports = responseFormatter
